package com.xlong.k329;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.fragment.NavHostFragment;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.xlong.k329.databinding.FragmentFirstBinding;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;
    private FloatingActionButton btn_fab;
    //LocalBroadcastManager broadcastManager;


    /*
    LayoutInflater inflater：作用类似于findViewById（），findViewById（）用来寻找xml布局下的具体的控件（Button、TextView等），LayoutInflater inflater（）用来找res/layout/下的xml布局文件
    ViewGroup container：表示容器，View放在里面
    Bundle savedInstanceState：保存当前的状态，在活动的生命周期中，只要离开了可见阶段，活动很可能就会被进程终止，这种机制能保存当时的状态
     */
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);//inflate将xml定义的一个布局找出来，但仅仅是找出来而且隐藏的，没有找到的同时并显示功能。用inflate()方法先将对话框的layout找出来，然后再用findViewById()找到它上面的其它组件。
        return binding.getRoot();//调用getRoot()方法获取对根视图的引用

    }


    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.txtQty.setText(MainActivity.helper.getString("qty") == null ? "1000":MainActivity.helper.getString("qty"));
        if(DeviceConnFactoryManager.getDeviceConnFactoryManager() != null && DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState() == true){
            binding.txtBlestatus.setText("已连接");
            binding.txtPrinterinfo.setText(getConnDeviceInfo());
            binding.txtPrinterinfo.setVisibility(View.VISIBLE);
            binding.buttonBluthscan.setVisibility(View.INVISIBLE);
            binding.buttonDisconnect.setVisibility(View.VISIBLE);
        }else{
            binding.txtBlestatus.setText("未连接");
            binding.txtPrinterinfo.setVisibility(View.INVISIBLE);
            binding.buttonBluthscan.setVisibility(View.VISIBLE);
            binding.buttonDisconnect.setVisibility(View.INVISIBLE);
        }
        btn_fab = (FloatingActionButton)getActivity().findViewById(R.id.fab);
        btn_fab.setVisibility(View.VISIBLE);
        binding.txtQty.addTextChangedListener(new EditChangedListener());
        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });

        binding.btnTestprint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManager() == null ||
                        !DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState()) {
                    Utils.toast(getActivity(), getString(R.string.str_cann_printer));
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("pname", "螺丝（圆头φ4×18）");
                bundle.putString("mname", "SCREW;6-32X3/4;PH;PHIL;SS;NYLK");
                bundle.putString("qrstr", "CDD10053R003&CG509&19870809/1234");
                MainActivity.sendCpcl(bundle);
                //MainActivity.getNewSn("1111&22222&33333");
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
        receiveAdDownload();
    }

    @Override
    public void onSaveInstanceState(Bundle outbundle){
        super.onSaveInstanceState(outbundle);
    }

    class EditChangedListener implements TextWatcher {
        // 输入文本之前的状态
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {

        }

        // 输入文字中的状态，count是一次性输入字符数
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        // 输入文字后的状态
        @Override
        public void afterTextChanged(Editable s) {
            MainActivity.helper.putValues(
                    new SharedPreferencesUtils.ContentValue("qty", s.toString()));
        }
    };

    /**
     * 注册广播接收器
     */
    private void receiveAdDownload() {
        //broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter filter = new IntentFilter();
        filter.addAction(DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        getActivity().registerReceiver(mReceiver, filter);
    }


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            switch (action) {
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            binding.txtBlestatus.setText("未连接");
                            binding.txtPrinterinfo.setVisibility(View.INVISIBLE);
                            binding.buttonBluthscan.setVisibility(View.VISIBLE);
                            binding.buttonDisconnect.setVisibility(View.INVISIBLE);
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            binding.txtBlestatus.setText("已连接");
                            binding.txtPrinterinfo.setText(getConnDeviceInfo());
                            binding.txtPrinterinfo.setVisibility(View.VISIBLE);
                            binding.buttonBluthscan.setVisibility(View.INVISIBLE);
                            binding.buttonDisconnect.setVisibility(View.VISIBLE);
                            break;
                        default:
                            break;
                    }
                    break;
                case DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE:

                    break;
                default:
                    break;
            }
        }
    };

    private String getConnDeviceInfo() {
        String str = "";
        DeviceConnFactoryManager deviceConnFactoryManager = DeviceConnFactoryManager.getDeviceConnFactoryManager();
        if (deviceConnFactoryManager != null
                && deviceConnFactoryManager.getConnState()) {
            if (deviceConnFactoryManager.getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH) {
                str += "蓝牙\n";
                str += "MAC地址: " + deviceConnFactoryManager.getMacAddress();
            } else if (deviceConnFactoryManager.getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.WIFI) {
                str += "WIFI\n";
                str += "ip: " + deviceConnFactoryManager.getIp() + "\n";
                str += "port: " + deviceConnFactoryManager.getPort();
            }
        }
        return str;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mReceiver);
        /*if(DeviceConnFactoryManager.getDeviceConnFactoryManager() != null && DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState() == true){
            DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
        }*/
        binding = null;
    }

}